//
//  ZMBMoreVC.swift
//  HengYouCai
//
//  Created by wll on 2018/5/9.
//  Copyright © 2018年 lwj. All rights reserved.
//  芝麻包更多界面--代码

import UIKit
import Kingfisher

//MARK:___Cell___
class JCWSafeGuardVCCell: UITableViewCell {
    
    //配置cell
    override func wl_configurationCell(_ modelTemp: Any?, _ listView: UIScrollView, _ indexPath: IndexPath) {
        if let dataArr = modelTemp as? [[[String]]]{
            self.imageView?.image = UIImage(named: dataArr[indexPath.section][1][indexPath.row])
            self.textLabel?.text = dataArr[indexPath.section][0][indexPath.row]
        }
    }
    //快捷生成cell
    static func wl_createCellWithTableView(_ tableView: UITableView) -> JCWSafeGuardVCCell {
        
        let cellID =
            NSStringFromClass(JCWSafeGuardVCCell.self);
        if let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? JCWSafeGuardVCCell {
            return cell
        }else{
            return JCWSafeGuardVCCell(style: .default, reuseIdentifier: cellID)
        }
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.textLabel?.font = Font_WL(14)
        self.textLabel?.textColor = Normal_333Color
        self.accessoryView = UIImageView(image: UIImage(named: "safe_ringht"))
        self.createContentView()
    }
    
    
    private func createContentView(){
        self.contentView .addSubview(self.redNumberLab)
        _ = self.redNumberLab.sd_layout().leftSpaceToView(self.imageView,3)?.topSpaceToView(self.imageView?.top_sd,10)?.widthIs(5)?.heightIs(5)
    }
    //小红点
    lazy var redNumberLab: UILabel = {
        let temp = UILabel()
        temp.textColor = UIColor.white
        temp.backgroundColor = UIColor.red
        temp.sd_cornerRadiusFromWidthRatio = 0.5
        temp.isHidden = true
        return temp
    }()
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}

//MARK:___VC___
class JCWSafeGuardVC: BaseTableViewController {
    
    deinit {
        debugPrint("更多界面释放了")
    }
    /// 接口数据
    var json: JSON?
    
    ///客服电话
    var phoneNumberStr: String = ""
    /// 安全保障
    var safeUrl: String = ""
    /// 公告中心
//    var
    ///公众号
    var wechatStr: String = ""
    
    ///公众号
    var appReviewLink: String = ""
    
    /// 帮助中心
    var helpCenterUrl: String = ""
    
    //数据
    fileprivate var dataArr = [
        [["关于我们","安全保障"],
         ["safe_introduce","safe_safe"]],
        [["公告中心","帮助中心"],
         ["safe_notice","safe_help"]],
        [["给子壹财富打分"],
         ["safe_mark"]],
        [["微信公众号：子壹财富"],
         ["safe_wechat"]
        ]
    ]
    //更改默认样式为
    convenience init() {
        self.init(style: .grouped)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.createNav()
        self.loadData()
    }
    let navTitle = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navTitle.textColor = UIColor.white
        navTitle.font = Font_WL(16)
        navTitle.textColor = Color.white
        navTitle.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navTitle.textAlignment = .center
//        navTitle.text = "更多"
//        navTitle.sizeToFit()
        self.navigationItem.titleView = navTitle
        
        // tableview自动下沉问题
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        self.createCV()
        self.view.jcw_showGifLoading()
        
        
        weak var weakSelf = self
        let header = LWRefreshGifHeader(refreshingBlock: {
            weakSelf?.loadData()
        })
        header?.stateLabel.textColor = Color.white
        header?.lastUpdatedTimeLabel.textColor = Color.white
        header?.isAutomaticallyChangeAlpha = true
        header?.ignoredScrollViewContentInsetTop = -kJcwStatuBarHeight() - 10
        self.tableView.mj_header = header
        self.tableView.bringSubview(toFront: header!)
        
        //顶部拉伸不为白色
        let bgLayer = CALayer()
        bgLayer.backgroundColor = ColorFromRGBHex_WL(0x3d3d3d).cgColor
        bgLayer.frame = CGRect(x: 0, y: -JCWSCREENH, width: JCWSCREENW, height: JCWSCREENH)
        self.tableView.layer.insertSublayer(bgLayer, at: 0)
    }
    
    func createNav() {
        // 导航栏透明
        self.navigationController?.navigationBar.setBackgroundImage( UIImage(named: "touming"), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
        
        self.navigationController?.navigationBar.subviews.first?.alpha = 0
    }
    
    func createCV() {
        //界面配置
        self.view.backgroundColor = BgView_f3f3f3Color
        self.tableView.tableHeaderView = self.headerView
        self.tableView.separatorColor = self.tableView.backgroundColor
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0)
        self.tableView.sectionFooterHeight = 0
        self.tableView.sectionHeaderHeight = 7.5.ah_wl
        self.tableView.rowHeight = 45
    }
    //刷新表头
    fileprivate func wl_reloadTableHeader(_ imageUrl: String!) {
        if let url = URL(string: imageUrl) {
            if let temp: UIButton = self.headerView.viewWithTag(100) as? UIButton {
                temp.kf_setBackgroundImage(with:  ImageResource(downloadURL: url), for: .normal, placeholder: UIImage(named: "safe_banner"), options: nil, progressBlock: nil, completionHandler: nil)
//                temp.kf.setBackgroundImage(with: ImageResource(downloadURL: url), for: .normal, placeholder: UIImage(named: "safe_banner"), options: nil, progressBlock: nil, completionHandler: nil)
            }
        }
    }
    
    //表头
    lazy var headerView: UIView = {
        let temp: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: (150 + kJcwGetNavHeight())))
        
        temp.backgroundColor = self.view.backgroundColor
        
        let contentView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: temp.height_sd - 35))
        contentView.backgroundColor = ColorFromRGBHex_WL(0x3d3d3d)
        temp.addSubview(contentView)
        //电话图片
        let btn: UIButton = UIButton(type: .custom)
        btn.frame = CGRect(x: 12, y: 0, width: contentView.width_sd - 24, height: 140)
        btn.bottom_sd = temp.height_sd - 13
        btn.tag = 100
        btn.setBackgroundImage(UIImage(named: "safe_banner"), for: .normal)
        btn.addTarget(self, action: #selector(tableHeaderClick), for: .touchUpInside)
        temp.addSubview(btn)
        return temp
    }()
    //区头点击方法
    func tableHeaderClick() {
        if !self.phoneNumberStr.isEmpty {
            UIAlertController(nil, self.phoneNumberStr, ["取消","拨打"],  [], .alert) { (index, str) in
                if index == 1 {
                    JCWCallTel(self.phoneNumberStr)
                }
            }
        }
    }
}



//表代理
extension JCWSafeGuardVC {
    
    override  func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArr.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr[section][0].count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> JCWSafeGuardVCCell {
        let cell = JCWSafeGuardVCCell.wl_createCellWithTableView(tableView)
        cell.wl_configurationCell(self.dataArr, tableView, indexPath)
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if 0 == indexPath.section {
            if 0 == indexPath.row {//关于我们
                guard let json = json else {return}
                
                let vc = UIStoryboard(name: "Profile", bundle: nil).instantiateViewController(withIdentifier: "AboutUsVCID") as! AboutUsVC
                vc.titleName = dataArr[indexPath.section][0][indexPath.row]
                vc.platformIntro = json["platformIntroLabel"].stringValue
                vc.platformIntroUrl = json["platformIntroUrl"].stringValue
                vc.feedback = json["feedbackLabel"].stringValue
                self.navigationController?.pushViewController(vc, animated: true)
                
                
                
            }else if 1 == indexPath.row{//安全保障
                self.navigationController?.pushViewController(BannerWebViewVC(urlStr: safeUrl, title: dataArr[indexPath.section][0][indexPath.row]), animated: true)
                
                
            }
        }else if 1 == indexPath.section {
            if 0 == indexPath.row{//公告中心
                let vc = ArticleListVC()
                vc.titleName = dataArr[indexPath.section][0][indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }else if 1 == indexPath.row{//帮助中心
                if helpCenterUrl.count > 0 {
                    self.navigationController?.pushViewController(BannerWebViewVC(urlStr: helpCenterUrl, title: "帮助中心"), animated: true)
                }
               
            }
        } else if 2 == indexPath.section {//打分
            if let url = URL(string: appReviewLink){
                //bug 不写这一句打不开 我也是醉了
                _ = JCWShareApplication.canOpenURL(url)
                JCWShareApplication.openURL(url)
            }
        }else if 3 == indexPath.section{//关注微信公众号
            if !self.wechatStr.isEmpty {
                JCWPasteboard(self.wechatStr)
                self.view.makeToast("已复制到粘贴板,请到微信上关注", duration: 1, position: CSToastPositionCenter)
            }
        }
    }
}


extension JCWSafeGuardVC {
    
    /// 数据请求
    fileprivate func loadData() {
        HYCNetService.moreMore(withDict: [:], onSuccess: { (result) in
            
            self.tableView.mj_header?.endRefreshing()
            //["phone": 400-600-0891, "artNoRead": 0, "wechat": jincaiwa, "phoneImgUrl": https://api.jincaiwa.com/res/website/images/phoneNumPic.png?v01]
            self.view.hideHUDLoading(0)
            let resultJson: JSON = JSON(result!)
            print(resultJson)
            self.json = resultJson
            
            self.navTitle.text = resultJson["title"].stringValue
            
            let aboutLabel = resultJson["aboutLabel"].stringValue
            let safeLabel = resultJson["safeLabel"].stringValue
            let noticeLabel = resultJson["noticeLabel"].stringValue
            let helpLabel = resultJson["helpLabel"].stringValue
            let scoreLabel = resultJson["scoreLabel"].stringValue
            let wechatLabel = resultJson["wechatLabel"].stringValue
            
            self.dataArr = [
                [[aboutLabel,safeLabel],
                 ["safe_introduce","safe_safe"]],
                [[noticeLabel,helpLabel],
                 ["safe_notice","safe_help"]],
                [[scoreLabel],
                 ["safe_mark"]],
                [[wechatLabel],
                 ["safe_wechat"]
                ]
            ]
            self.phoneNumberStr = resultJson["phone"].stringValue
            self.wechatStr = resultJson["wechat"].stringValue
            self.appReviewLink = resultJson["iOSLink"].stringValue
            self.wl_reloadTableHeader(resultJson["phoneImgUrl"].stringValue)
            self.helpCenterUrl = resultJson["helpCenterUrl"].stringValue
            self.safeUrl = resultJson["safeUrl"].stringValue
            
            ///消息未读数量处理
            if let cell: JCWSafeGuardVCCell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as? JCWSafeGuardVCCell {
                cell.redNumberLab.isHidden = resultJson["artNoRead"].intValue <= 0
            }
            self.tableView.reloadData()
            
        }) { (code, errMsg) in
            self.view.hideHUDLoading(0)
            self.tableView.mj_header?.endRefreshing()
        }
    }
}
